package net.vkits.controller;

import net.vkits.auth.application.PermissionApplicationService;
import net.vkits.auth.domain.model.Permission;
import net.vkits.common.Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by ethan-liu on 16/3/27.
 */
@Controller
@RequestMapping("/permissions")
public class PermissionController {
    private static final Logger log = LoggerFactory.getLogger(PermissionController.class);

    @Resource
    PermissionApplicationService permissionApplicationService;

    @RequiresPermissions("system:sys_permission:list")
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView permissions() {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        List<Permission> permissions = permissionApplicationService.getPermissions();
        log.info("size is: {}", permissions.size());
        modelMap.put("permissions", permissions);
        modelMap.put("treeview", "system");
        modelMap.put("sidebar", "permissions");
        modelMap.put("currentUser",username);
        return new ModelAndView("/permissions", modelMap);
    }

    @RequiresPermissions("system:sys_permission:list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<Permission> getPermissions() {
        List<Permission> permissions = permissionApplicationService.getPermissions();
        log.info("size is: {}", permissions.size());
        return permissions;
    }
}
